package com.xigege.netty.httpExample;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * 1. SimpleChannelInboundHandler就是原先写过的ChannelInboundHandlerAdapter的子类
 *      它提供的方法更多一些
 * 2. HttpObject 客户端和服务器端相互通讯的数据被封装成 HttpObject
 */
public class TestHttpServerHandle extends SimpleChannelInboundHandler<HttpObject> {
    //channelRead0：当有读取事件时触发，读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //判断 msg 是不是 httpRequest请求
        if (msg instanceof HttpRequest) {
            //每个浏览器对应的pipeline和handler是独立的，不会相互共享，
            //浏览器1 有一个pipeline和handler对应，那么浏览器2 有另外一个pipeline和handler对应
            System.out.println("pipeline hashCode" + ctx.pipeline().hashCode() + "TestHttpServerHandler hash=" + this.hashCode());

            System.out.println("msg的类型" + msg.getClass());
            System.out.println("客户端地址" + ctx.channel().remoteAddress());

            //获取到httpRequest
            HttpRequest httpRequest = (HttpRequest) msg;
            //获取到uri，过滤指定的资源
            URI uri = new URI(httpRequest.uri());
            //如果发现是请求的这个图标资源
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求了Favicon.ico,不做响应");
                return;
            }

            //回复信息给浏览器（http协议）
            ByteBuf content = Unpooled.copiedBuffer("hello 我是服务器", CharsetUtil.UTF_8);

            //构建一个http的响应，即httpResponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            //设置头
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());//content的长度

            //将构建好的response返回
            ctx.writeAndFlush(response);
        }
    }
}
